package per.hx.bs.web.sys.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import per.hx.bs.base.annotation.BsCLog;
import per.hx.bs.base.domain.ReturnDTO;
import per.hx.bs.base.entity.UserOnline;
import per.hx.bs.web.sys.service.SysSessionService;

import java.util.Collection;
import java.util.List;

/**
 * @author HuXing
 * @date 2018/3/25  17:17
 */

@RequestMapping("/sys/online")
@Controller
public class SessionController {


    private final
    SysSessionService sysSessionService;

    @Autowired
    public SessionController(SysSessionService sysSessionService) {
        this.sysSessionService = sysSessionService;
    }

    @BsCLog("查看在线用户")
    @RequiresPermissions("sys:online:list")
    @GetMapping(value = {"/", ""})
    public String online() {
        return "system/online/online";
    }


    @BsCLog("获取在线用户列表")
    @RequiresPermissions("sys:online:list")
    @RequestMapping("/list")
    @ResponseBody
    public List<UserOnline> list() {
        return sysSessionService.list();
    }

    @BsCLog("注销在线用户")
    @RequiresPermissions("sys:online:logout")
    @GetMapping(value = "/forceLogout/{sessionId}")
    @ResponseBody
    public ReturnDTO forceLogout(@PathVariable("sessionId") String sessionId) {
        try {
            if (sysSessionService.forceLogout(sessionId)) {
                return ReturnDTO.ok();
            } else {
                return ReturnDTO.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ReturnDTO.error();
        }

    }

    @BsCLog("批量注销在线用户列表")
    @RequiresPermissions("sys:online:logout")
    @GetMapping(value = "/forceLogout/batchForceLogout")
    @ResponseBody
    public ReturnDTO batchForceLogout(@RequestParam("sessionIdS[]") String[] sessionIdS) {
        try {
            int count = sysSessionService.batchForceLogout(sessionIdS);
            if (count > 0) {
                return ReturnDTO.ok("已经对" + count + "名用户进行注销操作。。");
            } else {
                return ReturnDTO.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ReturnDTO.error();
        }

    }

    @BsCLog("Session列表")
    @RequiresPermissions("sys:online:list")
    @GetMapping(value = "/sessionList")
    @ResponseBody
    public Collection<Session> sessionList() {
        return sysSessionService.sessionList();
    }

}
